import React, { createContext, useContext, useState, useMemo } from 'react';
import { ConfigProvider, theme as antdTheme, Spin } from 'antd';
import { setGlobalLoadingSetter } from '../api';

const AppContext = createContext(null);

export function AppProvider({ children }) {
  const [canvas, setCanvas] = useState([]);
  const [selectedIndex, setSelectedIndex] = useState(null);
  const [loading, setLoading] = useState(false);
  const [theme, setTheme] = useState('light'); // 'light' | 'dark'

  // 切换主题
  const toggleTheme = () => setTheme(t => (t === 'light' ? 'dark' : 'light'));

  // antd 主题算法
  const antdThemeConfig = useMemo(() => ({
    algorithm: theme === 'dark' ? antdTheme.darkAlgorithm : antdTheme.defaultAlgorithm,
  }), [theme]);

  React.useEffect(() => {
    setGlobalLoadingSetter(setLoading);
    return () => setGlobalLoadingSetter(null);
  }, []);

  return (
    <AppContext.Provider value={{
      canvas, setCanvas,
      selectedIndex, setSelectedIndex,
      loading, setLoading,
      theme, setTheme, toggleTheme
    }}>
      <ConfigProvider theme={antdThemeConfig}>
        <Spin spinning={loading} size="large" style={{ maxHeight: '100vh' }}>
          {children}
        </Spin>
      </ConfigProvider>
    </AppContext.Provider>
  );
}

export function useApp() {
  return useContext(AppContext);
} 